package com.push.common.utils;

import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CharsetUtil {
    //URLConnection从header中获取charset
    public static String getCharsetFromHeader(URLConnection con) {
        String charset = null;
        String contentType = con.getContentType();
        //先从header中取
        if(contentType!=null && contentType.toLowerCase().contains("charset")) {
            String line = contentType.toLowerCase();
            String[] ss = line.split(";");
            for(String s: ss) {
                if(s.contains("charset")) {
                    String[] chArr = s.split("=");
                    charset = chArr[1].trim();
                }
            }
        }
        return charset;
    }

    //httpclient从header中获取charset
    public static String getCharsetFromHeader(HttpEntity entity) {
        Charset ch = ContentType.getOrDefault(entity).getCharset();
        if(ch!=null) return ch.toString();
        return null;
    }

    //从网页字节数组中获取charset
    public static String getCharsetFromByteArray(byte[] bytes, String defaultCharset)
            throws IOException {
        String charset = null;
        //将字节数组转换为BufferedReader流
        InputStreamReader isr = new InputStreamReader(new
                ByteArrayInputStream(bytes),defaultCharset);
        BufferedReader br = new BufferedReader(isr);

        //从流中读取charset
        String temp = null;
        while((temp = br.readLine())!=null) {
            //如果读取到了charset或者head标签已经结束，那么不再继续读取
            if(temp.toLowerCase().contains("charset") ||
                    temp.toLowerCase().contains("</head>")) {
                charset = CharsetUtil.getCharset4Line(temp);
                break;
            }
        }
        br.close();

        //如果未读取到charset，返回默认charset
        charset = (charset==null ? defaultCharset : charset);
        return charset;
    }

    //从字符串中解析出charset
    public static String getCharset4Line(String line) {
        String charset = null;
        String regex = "charset=\"?(.+?)\\s?\"?\\s?/?>";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(line);
        if(matcher.find()) {
            charset = matcher.group(1).trim();
        }
        return charset;
    }
}
